<?php

namespace app\api\controller;

use app\admin\model\express\Banner;
use app\admin\model\express\Warehouse;
use app\admin\model\OrderExpress;
use app\common\controller\Api;
use app\common\library\Express100;
use baiduapi\AipNlp;
use common\models\MallOrderExpress;
use think\Config;
use think\Db;

/**
 * 首页接口
 */
class Query extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    public $app_key = "XGBCri93MP4c7tjpSDfb";
    public $app_secret = "JgUxINmIzfQL23TGEvaSx3Rh9l";


    public function sign(){
        $order_no = $this->request->param('order_no');
        if(empty($order_no)){
            $this->res_error("缺少参数");
        }
        $sign = $this->getSign($order_no);

        $this->res_success('ok',['sign'=>$sign]);
    }

    public function getSign($express_no){
        return md5($this->app_key.$express_no.$this->app_secret);
    }


    public function log()
    {
        $get = $this->request->get();
        $post = $this->request->post();
        $row = $this->request->getInput();

        $data = [
            'post' => $post?json_encode($post,JSON_UNESCAPED_UNICODE):'',
            'get' => $get?json_encode($get,JSON_UNESCAPED_UNICODE):'',
            'row' => $row,
            'type'=>'index',
            'time_str'=>date('y-m-d H:i:s'),
            'ip' => $this->request->ip(),
        ];
        return Db::name('log')->insertGetId($data);
    }

    public function setLogError($log_id,$error)
    {
        return Db::name('log')->where(['id'=>$log_id])->update(['error'=>$error]);
    }

    //获取物流信息
    public function index(){
        $state_ar = [
            '0'=>'在途',
            '1'=>'揽收',
            '2'=>'疑难',
            '3'=>'签收',
            '4'=>'退签',
            '5'=>'派件',
            '6'=>'退回',
            '7'=>'转单',
            '10'=>'待清关',
            '11'=>'清关中',
            '12'=>'已清关',
            '13'=>'清关异常',
            '14'=>'收件人拒签等'
        ];

        if(!$this->request->isPost()){
            $this->res_error("请使用post请求");
        }
        $log_id = $this->log();
        $order_no = $this->request->post('num','','trim');
        $key = $this->request->post('key','','trim');
        $sign = $this->request->post('sign','','trim');
        $test = $this->request->post('test','','trim');
        if(empty($order_no)){
            $this->setLogError($log_id,"运单号不能为空");
            $this->res_error("运单号不能为空");
        }
        if(empty($key)){
            $this->setLogError($log_id,"key不能为空");
            $this->res_error("key不能为空");
        }
        if(empty($sign)){
            $this->setLogError($log_id,"sign不能为空");
            $this->res_error("sign不能为空");
        }
        if($key != $this->app_key){
            $this->setLogError($log_id,"key效验失败");
            $this->res_error("key效验失败");
        }
        $check_sign = $this->getSign($order_no);
        if($check_sign != $sign){
            $this->setLogError($log_id,"sign效验失败");
            $this->res_error("sign效验失败");
        }

        $order = Db::name("order")->where(['order_no'=>$order_no])->find();
        if(empty($order)){
            $order = Db::name("order")->where(['express_no'=>$order_no])->find();
        }

        $state = 5;
        $express_arr = [];
        if($order && $order['express_no']){
            try{
//                $expressData = $this->getExpressData($order_no);
                $mobile = $order['to_mobile']?:$order['from_mobile'];
                $expressData = $this->setExpressData($order['express_no'],$mobile);
            }catch (\Exception $e){
                $this->setLogError($log_id,$e->getMessage());
                $this->res_error($e->getMessage());
            }
            if($expressData && isset($expressData['data']) && !is_array($expressData['data'])){
                $expressData['data'] = json_decode($expressData['data'],true);
            }
            if($expressData && isset($expressData['data']) && is_array($expressData['data'])){
                foreach ($expressData['data'] as $val){
                    $express_arr[] = [
                        'context'=>$val['context'],
                        'location'=>'',
                        'time'=>$val['time'],
                    ];
                }
            }

            array_push($express_arr,['time'=>date("Y-m-d H:i:s",$order['createtime']),'context'=>'全一物流已转出下一站','location'=>'']);
        }else{
            $state = 12;
            if($order){
                $list = Db::name("order_track_log")->where(['order_no'=>$order['order_no']])->order("time desc")->select();
                foreach ($list as &$val){
                    $val['time'] = date("Y-m-d H:i:s",$val['time']);
                    $express_arr[] = [
                        'context'=>$val['msg'],
                        'location'=>'',
                        'time'=>$val['time'],
                    ];
                }
               // array_push($express_arr,['time'=>date("Y-m-d H:i:s",$order['createtime']),'context'=>'全一物流已转出下一站']);
            }

            if($test=='123123'){
                p($express_arr);die;
            }
        }

        $arr = [];
        if($express_arr && is_array($express_arr)){
            foreach ($express_arr as $k=> &$val1){
                if(strpos($val1['context'],"聊城") !== false){
                    unset($express_arr[$k]);
                    continue;
                }
                $val1['context'] = strtr($val1['context'],['电话：'=>'','联系电话：'=>'','安能'=>'','安能物流'=>'']);
                $val1['context'] = strtr($val1['context'],['电话'=>'','联系电话'=>'']);
                $val1['context'] = preg_replace_callback("/1\d{10}/",function ($match){
                    return "";
                },$val1['context']);
                $val1['context'] = preg_replace_callback("/[-0-9]/",function ($match){
                    return "";
                },$val1['context']);
                $val1['context'] = strtr($val1['context'],['【】'=>'']);

                $arr[] = $val1;
            }
        }
        $arr = $arr?:$express_arr;
        Db::name("log")->where(['id'=>$log_id])->update(['res'=>json_encode($arr,JSON_UNESCAPED_UNICODE)]);
        $this->res_success("SUCCESS",$arr,$state);
    }

    public function res_success($msg,$data,$state=-1){
        header("Content-type:application/json;charset=utf8");

        $data = [
            'message'=>$msg?:"SUCCESS",
            'result'=>true,
            'data'=>$data,
        ];
        if($state>=0){
            $data['state'] = $state;
        }

        echo json_encode($data,true); exit();
    }

    public function res_error($msg,$data=[]){
        header("Content-type:application/json;charset=utf8");

        $data = [
            'message'=>$msg,
            'result'=>false,
            'data'=>$data,
        ];

        echo json_encode($data,true); exit();
    }

    //获取物流信息
    public function getExpress1(){
        $express_no = "772023524061625";
        $express_no = "SF1242747902731";  //15936258797

        $express_no = "500148036629";

        $expressData = null;
        try{
            $expressData = $this->getExpressData($express_no);
            $expressData = null;
            if(empty($expressData)){
                $expressData = $this->setExpressData($express_no);
            }

        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        if($expressData && isset($expressData['data']) && !is_array($expressData['data'])){
            $expressData['data'] = json_decode($expressData['data'],true);
        }
        if(isset($expressData['data']) && is_array($expressData['data'])){
            foreach ($expressData['data'] as $k=>&$val){
                if(strpos($val['context'],"聊城") !== false){
                    unset($expressData['data'][$k]);
                    continue;
                }
                $val['context'] = strtr($val['context'],['电话：'=>'','联系电话：'=>'','安能'=>'','安能物流'=>'']);
                $val['context'] = strtr($val['context'],['电话'=>'','联系电话'=>'']);
                $val['context'] = preg_replace_callback("/1\d{10}/",function ($match){
                    return "";
                },$val['context']);
                $val['context'] = preg_replace_callback("/[-0-9]/",function ($match){
                    return "";
                },$val['context']);
                $val['context'] = strtr($val['context'],['【】'=>'']);
            }
        }

        $this->success("ok",['list'=>$expressData]);
    }


    /** 获取订单物流信息
     * @param $orderSn
     * @param $express_number
     * @return bool|mixed
     */
    private  function getExpressData($express_number){
        $data= Db::name("order_express")->where(['express_number'=>$express_number])->find();
        if(empty($data) || empty($data['data'])) return false;
        //超过五个小时，不再使用数据库数据
        $nowTime = time();
        if(($nowTime - $data['updatetime'])>3600*6) return false;
        return $data;
    }


    /** 设置，存储物流信息
     * @param $order_id
     * @param $express_number
     * @return bool|mixed
     * @throws \Exception
     */
    private  function setExpressData($express_number,$mobile = ''){
        if(empty($express_number)){
            throw new \Exception('参数有误');
        }

        $data =  Express100::getExpressInfo($express_number,$mobile);
        if(empty($data) || empty($data['data'])){
            throw new \Exception($data['message']??'还未有物流信息');
        }
        $info = Db::name("order_express")->where(['express_number'=>$express_number])->find();
        $nowTime = time();
        if($info){
            Db::name("order_express")->where(['id'=>$info['id']])->update(['data'=>json_encode($data,JSON_UNESCAPED_UNICODE),'updatetime'=>$nowTime]);
        }else{
            $model = new OrderExpress();
            $datas =[
                'order_no'=>'',
                'express_number'=>$express_number,
                'express_name'=>"",
                'data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'createtime'=>$nowTime,
                'updatetime'=>$nowTime
            ];
            $model->allowField(true)->save($datas);
        }
        return $data;
    }

    //百度api接口地址纠错
    public function baidu(){
        $app_id = '23175914';
        $api_key = 'hvzfnKz0ezMmmwcFSSE0n6a9';
        $secret_key = 'aSQMc41mTGd0sOOyOTTYgqD2VTMFkqp0';
        $client =  new AipNlp($app_id,$api_key,$secret_key);
        $text = "河南 郑州 中原区 北林路 政七街";
        $text = "收货人: 陈先生手机号码: 13306956707所在地区: 福建省漳州市龙文区详细地址: 九龙大道万达广场小区c区1号楼2单元905室";
        // 调用地址识别接口
        $data = $client->address($text);
        p($data);die;
    }

    public function test(){
        $eg_data = [
            'id'=>1,
            'order'=>[
                'from_express_no'=>'a',
                'weight'=>'10',
                'line_id'=>'1',
                'insure_price'=>'100',
                'tax_price'=>200,
                'post_price'=>200,
                'goods_list'=>[
                    ['name'=>'华为手机','number'=>'1','brand'=>'华为']
                ],
            ],
            'from_address'=>[
                'from_username'=>'zdw',
                'from_mobile'=>'132456789',
                'from_email'=>'123@qq.com',
                'from_address'=>'adfsd',
                'from_post_code'=>'1122',
            ],
            'to_address'=>[
                'to_username'=>'aa',
                'to_mobile'=>'122333333',
                'to_province'=>'河南',
                'to_city'=>'郑州',
                'to_district'=>'金水区',
                'to_address'=>'花园路10号',
                'to_post_code'=>'33366',
                'to_id_code'=>'11111111',
                'to_id_z_image'=>'/upload/a.png',
                'to_id_f_image'=>'/upload/b.png',
            ],
        ];

        echo json_encode($eg_data,JSON_UNESCAPED_UNICODE);die;
    }


}
